package middle;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Solution_382 {

    static class Solution {

        private ListNode head;
        private Random random = new Random();
        
        public Solution(ListNode head) {
            this.head = head;
        }

        public int getRandom() {
            int count = 1;
            ListNode node = this.head, rst = null;
            while (node != null) {
                int n = random.nextInt(count);
                if (n == 0) {
                    rst = node;
                }
                node = node.next;
                count++;
            }
            return rst.val;
        }
    }

    static class Solution_2 {

        private int size = 0;
        private ListNode head;
        private Random random = new Random();

        public Solution_2(ListNode head) {
            this.head = head;
            while (head != null) {
                size++;
                head = head.next;
            }
        }

        public int getRandom() {
            int count = random.nextInt(size);
            ListNode node = this.head;
            while (count-- > 0) {
                node = node.next;
            }
            return node.val;
        }
    }

    static class Solution_1 {

        private List<ListNode> list;
        private Random random = new Random();

        public Solution_1(ListNode head) {
            list = new ArrayList<>();
            while (head != null) {
                list.add(head);
                head = head.next;
            }
        }

        public int getRandom() {
            return list.get(random.nextInt(list.size())).val;
        }
    }

    static class ListNode {

        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
